package com.stardust.common;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object obj = request.getSession().getAttribute("user");
        String uri = request.getRequestURI();
        System.out.println("uri="+uri);
        //在uri里搜索login或regist以确定是否为登录或注册
        if (!(uri.indexOf("login") > 0 || uri.indexOf("regist")>0)){
            String project = uri.substring(0,uri.indexOf("/welcome"));//截取uri里/welcome前的字符串定位项目名

            if (obj == null){
                response.sendRedirect(project+"/login.html");// 未获取到用户数据则重定位到登录页面
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
